package com.boot.unity.api.wx.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson.JSONObject;
import com.boot.unity.api.wx.entity.UserInfo;
import com.boot.unity.api.wx.entity.WxLoginInfo;
import com.boot.unity.api.wx.service.WxAuthService;
import com.boot.unity.api.wx.utils.IpUtil;
import com.boot.unity.api.wx.utils.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


/**
 * 鉴权服务
 */
@RestController
@RequestMapping("/wx/auth")

public class WxAuthController {

    @Autowired
    private WxMaService wxService;

    @Autowired
    private WxAuthService wxAuthService;


    /**
     * 微信登录
     *
     * @param wxLoginInfo 请求内容，{ code: xxx, userInfo: xxx }
     * @param request     请求对象
     * @return 登录结果
     */
    @PostMapping("login_by_weixin")
    public Object loginByWeixin(@RequestBody WxLoginInfo wxLoginInfo, HttpServletRequest request) {
        String code = wxLoginInfo.getCode();
        UserInfo userInfo = wxLoginInfo.getUserInfo();
        if (code == null || userInfo == null) {
            return ResponseUtil.badArgument();
        }

        String sessionKey = null;
        String openId = null;
        try {
            WxMaJscode2SessionResult result = this.wxService.getUserService().getSessionInfo(code);
            sessionKey = result.getSessionKey();
            openId = result.getOpenid();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (sessionKey == null || openId == null) {
            return ResponseUtil.fail();
        }
        String ipAddr = IpUtil.getIpAddr(request);
        JSONObject jsonObject = wxAuthService.wxLoginAuth(openId, sessionKey, userInfo, ipAddr);

        return jsonObject;
    }

    /**
     * 请求注册验证码
     *
     * TODO
     * 这里需要一定机制防止短信验证码被滥用
     *
     * @param body 手机号码 { mobile }
     * @return
     */
    @PostMapping("regCaptcha")
    public Object registerCaptcha(@RequestBody String body) throws Exception {
        return wxAuthService.registerCaptcha(body);
    }

    @PostMapping("checkLoginByWeixin")
    public Object checkLoginByWeixin(@RequestBody String body){
        return wxAuthService.checkLoginByWeixin(body);
    }

    @GetMapping("wxInfoById")
    @PostMapping("wxInfoById")
    public Object wxInfoById(String uid,String key){
        return wxAuthService.wxInfoById(uid,key);
    }

}
